<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Ynote extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->model('users');
        $this->load->model('posts');
        $this->load->helper('url');
    }

    public function index() {
        if ($this->session->userdata('logged_in')) {
            $data = array();
            $data['userPosts'] = $this->posts->getUserPost($this->session->userdata('logged_in')['userId']);
            $this->load->view('home', $data);
        } else {
            $this->load->view('index');
        }
    }

    public function login() {

        $submit = $this->input->post('login');
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        if ($submit && $username && $password && !$this->session->userdata('logged_in')) {
            $login = $this->users->login($username, $password);
            if ($login) {
                $session_array = array('userId' => $login[0]['id'], 'username' => $username);
                $this->session->set_userdata('logged_in', $session_array);
                redirect(base_url());
            }
        } else {
            redirect(base_url());
        }
    }

    function logout() {
        $this->users->logout();
    }

    public function register() {
        $this->load->view('register');
    }

    public function doComment() {
        $submit = $this->input->post('doComment');
        $comment = $this->input->post('comment');
        $postId = $this->input->post('postId');
        $current_url = $this->input->post('current_url');
        $userId = 0;

        if ($this->session->userdata('logged_in')['userId']) {
            $userId = $this->session->userdata('logged_in')['userId'];
        }

        if ($submit && $comment && $postId && $userId) {
            $query = $this->posts->insertComment(array('postId' => $postId, 'userId' => $userId, 'comment' => $comment));
            if ($query) {
                echo 'aaa'.$current_url;                
//redirect($current_url);
            }
        }
    }

}
